package com.example.movie.ui.user.setting

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.preference.Preference
import androidx.preference.Preference.OnPreferenceChangeListener
import androidx.preference.Preference.OnPreferenceClickListener
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.example.movie.R
import com.example.movie.data.user.login.model.SharedLoginViewModel
import com.example.movie.ui.MainActivity
import com.example.movie.utils.ContextHolder
import com.example.movie.utils.ToastUtil
import com.example.movie.utils.cache.CacheUtil
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_setting.*


class SettingActivity : AppCompatActivity() {

    private val logoutViewModel: SharedLoginViewModel = ContextHolder.from(MainActivity::class).loginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_setting)
        setUpObserver()
        setFragment()
        initViewEvent()
    }

    private fun setUpObserver() {
        logoutViewModel.logoutResult.observe(this, {
            it?.success?.let {
                ToastUtil.toast(this, "注销成功!")
                logoutViewModel.clearLogoutResult()
                setResult(Activity.RESULT_OK)
                finish()
            }
        })

    }

    private fun initViewEvent() {
        back.setOnClickListener {
            onBackPressed()
        }
        if (logoutViewModel.isLoggedIn()) {
            logout.visibility = View.VISIBLE
        }
        logout.setOnClickListener {
            QMUIDialog
                .MessageDialogBuilder(this)
                .setTitle("温馨提示")
                .setMessage("确认退出登录吗?")
                .addAction("取消") { _dialog: QMUIDialog, _: Int ->
                    _dialog.dismiss()
                }
                .addAction("确定") { _dialog: QMUIDialog, _: Int ->
                    logoutViewModel.logout()
                    _dialog.dismiss()
                }
                .show()
        }
    }

    private fun setFragment() {
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.settings, PreferenceFragment())
            .commit()
    }

    class PreferenceFragment : PreferenceFragmentCompat() {

        @SuppressLint("RestrictedApi")
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)
            clearAppCache()
            switchDarkMode()
            shareWithFriends()
        }

        private fun shareWithFriends() {
            val preference = findPreference<Preference>("shard_with_friend")!!
            preference.onPreferenceClickListener = OnPreferenceClickListener {
                QMUIBottomSheet
                    .BottomGridSheetBuilder(requireContext())
                    .addItem(R.drawable.icon_wechat,"分享到微信","分享",
                        QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                    .addItem(R.drawable.icon_goup_of_friends,"分享到朋友圈","分享",
                        QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                    .addItem(R.drawable.icon_weibo,"分享到微博","分享",
                        QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                    .build()
                    .show()

                return@OnPreferenceClickListener true
            }
        }

        private fun clearAppCache() {
            val clearCache = findPreference<Preference>("clear_cache")!!
            //计算缓存大小
            clearCache.summary = CacheUtil.getTotalCacheSize(requireContext())

            clearCache.onPreferenceClickListener = object : OnPreferenceChangeListener,
                OnPreferenceClickListener {

                override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
                    return true
                }

                override fun onPreferenceClick(preference: Preference?): Boolean {
                    QMUIDialog
                        .MessageDialogBuilder(context)
                        .setTitle("温馨提示")
                        .setMessage("确认删除缓存吗?")
                        .addAction("取消") { _dialog: QMUIDialog, _: Int ->
                            _dialog.dismiss()
                        }
                        .addAction("确定") { _dialog: QMUIDialog, _: Int ->
                            CacheUtil.cleanApplicationData(requireContext())
                            ToastUtil.makeTextShort(requireContext(), "清除缓存成功!")
                            clearCache.summary = CacheUtil.getTotalCacheSize(requireContext())
                            _dialog.dismiss()
                        }
                        .show()
                    return true
                }
            }
        }

        /**
         * 切换白天/黑夜模式
         */
        private fun switchDarkMode() {
            val darkMode = findPreference<SwitchPreferenceCompat>("dark_mode")!!
            darkMode.onPreferenceChangeListener =
                OnPreferenceChangeListener { _, newValue ->
                    if (newValue as Boolean) {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                    } else {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                    }
                    return@OnPreferenceChangeListener true
                }
        }
    }


    /**
     * 菜单选中/点击事件
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                false
            }
            else -> super.onOptionsItemSelected(item)
        }
    }


}



